package com.peng.wx_official_account.task;

import com.peng.wx_official_account.entity.dto.WeChatPushDto;
import com.peng.wx_official_account.entity.dto.YmlModel;
import com.peng.wx_official_account.entity.enums.WeChatPushTemplateEnum;
import com.peng.wx_official_account.entity.pojo.WxPushUser;
import com.peng.wx_official_account.service.WxPushUserService;
import com.peng.wx_official_account.service.impl.WeChatPushDataService;
import com.peng.wx_official_account.service.impl.WeChatPushImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class Task {

    private final YmlModel ymlModel;

    private final WeChatPushImpl service;
    private final WxPushUserService wxPushUserService;
    private final WeChatPushDataService weChatPushDataService;


    /**
     * Gets we chat token.
     * <p>
     * 定时获得WeChat-Token  100min刷新一次
     */
    @Scheduled(fixedDelay = 1000 * 60 * 100)
    public void getWeChatToken() {
        service.refreshToken();
    }

    /**
     * We chat push.
     * <p>
     * 微信公众号定时推送
     */
    @Scheduled(cron = "0 0 7 * * ?")
    @Retryable(value = Exception.class)
    public void weChatPush() {
        log.info("开始推送公众号消息");
        //创建推送对象
        WeChatPushDto weChatPushDto = new WeChatPushDto();

        //设置推送的appId和模板
        weChatPushDto.setAppid(ymlModel.getAppId()).setTemplate_id(WeChatPushTemplateEnum.TEMPLATE_WXY_TWO.getTemplate());

        //设置推送的数据 (该数据要对应推送的模板)
        weChatPushDto.setData(weChatPushDataService.templatesOfWXYPlus());

        //指定要推送的人
        List<String> list = new ArrayList<String>() {{
            this.add("王晓怡");
            this.add("吕浚鹏");
        }};

        //查询出要推送的人并获得该人员的openId
        List<WxPushUser> pushUserList = wxPushUserService.lambdaQuery().in(WxPushUser::getRemark, list).list();

        //调用推送接口进行推送
        for (WxPushUser user : pushUserList) {
            weChatPushDto.setTouser(user.getOpenId());
            //11月13日停止消息推送
            service.pushMsdData(weChatPushDto);
        }

        //LJP推送
        WeChatPushDto pushDto = new WeChatPushDto().setTemplate_id(WeChatPushTemplateEnum.TEMPLATE_LJP.getTemplate())
                .setAppid(ymlModel.getAppId())
                .setData(weChatPushDataService.templatesOfLJPAndCKT(0))
                .setTouser("onlQ562TaIaI0cW1nt1tJiHu-zmQ");
        service.pushMsdData(pushDto);

        log.info("推送结束");
    }

}
